home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: [Q] Porting to ANSI C
- Date: Tue, 23 Jan 96 13:22:31 GMT
- Organization: none
- Message-ID: <822403351snz@genesis.demon.co.uk>
- References: <DLLv31.Au2@news.zippo.com>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <DLLv31.Au2@news.zippo.com> john "John Muller" writes:
-
- >
- >Hi,
- >
- >We are attempting to port existing code to ANSI C. However, we have
- >many instances of something like this:
- >
- >typedef struct {
- > :
- > int len;
- > char data[0];
- >}
-
- This looks like an example of what is known as the 'struct hack'. This
- idea is to allocate (using malloc etc.) a variable sized structure depending
- on the size of the data array. Strictly you can't do this in ANSI C because
- every object type must have a length that is known at compile time (there
- has been much debate on this in the past on comp.std.c). However even though
- it is not strictly ANSI C you can still do something like this very
- portably (section 2.6 of the FAQ covers this question). Possibly the best
- approach is something like the following:
-
- #include <stddef.h>
-
- #define HACK_MAX_DATA_SIZE 1000 /* Or whatever value is appropriate */
- #define HACK_ALLOC_SIZE(datasize) (offsetof(struct hack, data) + (datasize))
-
- struct hack {
- ...
- int len;
- char data[HACK_MAX_DATA_SIZE];
- };
-
-
- Then in the program you can use something like:
-
- struct hack *hptr = malloc(HACK_ALLOC_SIZE(numchars));
-
- The reason for making the declared size of .data HACK_MAX_DATA_SIZE instead
- of, say, 1 is to tell the compiler what range of offsets it has to support
- for pointer arithmetic. It would be possible (and legal) for a smart
- compiler to notice that an object is 'small' and use some sort of efficient
- 'small' pointer arithmetic calculation.
-
- Again, this has been deemed not strictly conforming by the language committee
- but even so you should have no trouble using it in practice, so long
- as you don't ever do anything that relies on sizeof(struct hack) such as
- structure assignment or making it part of another struct/union/array.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-